<template>
  <div class="admin-container"> 
    <PanelHead :route="route" />
 </div>
 
  <div class="admin-container">
    <el-table :data="tableData.list">
      <el-table-column label="ID" prop="id" />
      <el-table-column label="昵称" prop="name" />
      <el-table-column label="所属组别" prop="permissions_id" >
        <template #default="scope">
          {{ permissionName(scope.row.permissions_id) }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" prop="mobile" />
      <el-table-column label="状态" prop="active" width="80px">
        <template #default="scope">
          <el-tag :type="scope.row.active ? 'success' : 'danger'">{{scope.row.active? '正常' : '失效'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" >
        <template #default="scope">
          <span>{{scope.row.create_time}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <!-- 修复：传递当前行数据给open函数 -->
          <el-button @click="open(scope.row)" type="primary">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加分页组件 -->
    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="tableData.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />
    
    <!-- 添加编辑对话框 -->
    <el-dialog v-model="dialogFormVisible" title="编辑管理员" :before-close="beforeClose">
      <el-form 
        ref="formRef"
        :model="form" 
        label-width="120px" 
        :rules="rules"
      >
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.mobile" />
        </el-form-item>
        <el-form-item label="所属组别" prop="permissions_id">
          <el-select v-model="form.permissions_id" >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { authAdmin, menuSelectList, userUpdate } from '../../api/index.js'
import { reactive, onMounted, ref, nextTick } from 'vue';
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs';
import PanelHead from '../../components/panelHead.vue';
import { useRoute } from 'vue-router';

const route = useRoute()

const tableData = reactive({
  list: [],
  total: 0
})

const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  getListData()
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.pageNum = val
  getListData()
};

const getListData = () => {
  authAdmin(pagination).then(({data}) => {
    console.log(data, 'admin data');
    const {list , total} = data.data
    list.forEach(element => {
      element.create_time = dayjs(element.create_time).format('YYYY-MM-DD')
    });
    tableData.list = list
    tableData.total = total
  });
}

//弹窗
const dialogFormVisible = ref(false)
const formRef = ref(null)

const beforeClose = () => { 
  dialogFormVisible.value = false
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

//编辑表单
const form = reactive({
  id: '',
  name: '',
  mobile: '',
  permissions_id: '',
})

const options = ref([])

const permissionName = (id) => {
  const data = options.value.find(item => item.id === id)
  return data ? data.name : '超级管理员'
}

const open = (rowData) => {
  if (rowData) {
    // 先设置对话框可见
    dialogFormVisible.value = true
    
    // 在下一个DOM更新周期设置表单数据
    nextTick(() => {
      Object.assign(form, {
        id: rowData.id || '',
        mobile: rowData.mobile || '',
        name: rowData.name || '',
        permissions_id: rowData.permissions_id || ''
      })
      
      // 验证formRef是否正确设置
      console.log('formRef in open:', formRef.value)
    })
  } else {
    ElMessage.warning('未找到行数据')
  }
}

const confirm = async () => {
  // 检查formRef是否正确设置
  console.log('formRef in confirm:', formRef.value)
  
  if (!formRef.value) {
    ElMessage.error('表单未正确初始化，请稍后重试')
    return
  }
  
  try {
    // 使用 Promise 包装 validate 方法
    const valid = await new Promise((resolve) => {
      formRef.value.validate((valid) => {
        resolve(valid)
      })
    })
    
    if (!valid) {
      ElMessage.warning('请检查表单填写是否正确')
      return
    }
    
    const {name, permissions_id, id} = form
    const res = await userUpdate({id, name, permissions_id})
    
    if(res.data.code === 10000){
      ElMessage.success('修改成功!')
      dialogFormVisible.value = false
      getListData()
    } else {
      ElMessage.error('修改失败: ' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新失败: ' + error.message)
  }
}

const rules = reactive({
  name: [
    { required: true, 
      message: '请输入昵称', 
      trigger: 'blur' },
  ],
  permissions_id: [
    { required: true, message: '请选择菜单权限', trigger: 'blur' },
  ]
})

onMounted(() => {
  getListData()
  menuSelectList().then(({data}) => { 
    options.value = data.data;
  })
});

</script>

<style scoped>
.admin-container {
  padding: 20px;
}
</style>
